import {
  Column,
  Entity,
  ManyToMany,
  ManyToOne,
  JoinColumn,
  JoinTable,
  AfterLoad,
  OneToOne,
  PrimaryColumn,
  BeforeInsert,
  BeforeUpdate,
  OneToMany,
} from 'typeorm';
import { v4 as uuidv4 } from 'uuid';
import * as moment from 'moment';
import { AccountEntity } from 'src/module/account/entities/account.entity';
import { EssayEntity } from 'src/module/essay/entities/essay.entity';
import { TagEntity } from 'src/module/tag/entities/tag.entity';
import { DrawEntity } from 'src/module/draw/entities/draw.entity';

@Entity({ name: 'user' })
export class UsersEntity {
  @PrimaryColumn()
  id: string = uuidv4();

  @Column({
    type: 'varchar',
    length: 30,
    nullable: false,
    unique: true,
  })
  username: string;

  @Column({
    type: 'varchar',
    length: 200,
    nullable: true,
  })
  headPicture: string;

  @Column({
    type: 'varchar',
    length: 100,
    nullable: true,
  })
  saying: string;

  @AfterLoad()
  afterLoad() {
    if (!this.headPicture) {
      this.headPicture =
        'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.alicdn.com%2Fi4%2F2204484777%2FO1CN01l3OVic1l9ufSylfAj_%21%212204484777.jpg&refer=http%3A%2F%2Fimg.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1675046478&t=2f817922272f32dad56eb18044afe38f';
    }
    if (!this.saying) {
      this.saying = '他太懒了，还没有留下签名';
    }
  }

  @Column({
    type: 'varchar',
    name: 'password',
    length: 100,
    nullable: false,
    select: false,
    comment: '密码',
  })
  password: string;

  @OneToOne(() => AccountEntity, (account) => account.user, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'account_id' })
  account: AccountEntity;

  @OneToMany(() => EssayEntity, (essay) => essay.user)
  essays: EssayEntity[];

  @OneToMany(() => DrawEntity, (draw) => draw.user)
  draws: DrawEntity[];

  @OneToMany(() => TagEntity, (tag) => tag.user)
  tags: TagEntity[];

  @Column({ type: 'varchar', nullable: true })
  created_at: string;

  @Column({ type: 'varchar', nullable: true })
  updated_at: string;

  @BeforeInsert()
  createDates() {
    this.created_at = moment().format('YYYY-MM-DD HH:mm:ss');
  }

  @BeforeUpdate()
  updateDates() {
    this.updated_at = moment().format('YYYY-MM-DD HH:mm:ss');
  }
}
